﻿using System;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using Framework.Library.Core.Config;
using Framework.Library.Data.DAL;
using ServiceStack.Text;
using Framework.Library.Data.DAO;
using System.Configuration;
using Framework.Library.Base.Helper;
using Framework.Library.Core.Utils.GlobalHelper;

namespace Framework.Library.Base.Extensions
{
    public static class SessionHelper
    {
        private static readonly ConfigHelper cfg = new ConfigHelper();
        private static string CURRENT_PORTAL = cfg.PrefixMember.VALUE + "CURRENT_PORTAL_{0}";
        private static string WORKING_PORTAL = cfg.PrefixMember.VALUE + "WORKING_PORTAL";
        private static string PORTAL = cfg.PrefixMember.VALUE + "PORTAL";
        private const string ACCOUNTID = "UserID";
        private const string ACCOUNTNAME = "UserName";
        private const string ACCOUNTINFO = "AccountInfo";
        private const string _CODE = "&code&";
        private const string _ACCESSSTOKEN = "&accesstoken&";
        private const string _EXPRISEDATE = "&exprisedate&";

        public static bool IsOnline(this HttpSessionState state)
        {
            if (state != null && (state[ACCOUNTID] != null || state[ACCOUNTNAME] != null))
                return true;
            return false;
        }
        public static int GetAccountId(this HttpSessionState state)
        {
            if (state != null && (state[ACCOUNTID] != null || state[ACCOUNTNAME] != null))
                return Convert.ToInt32(state[ACCOUNTID]);
            return -1;
        }
        public static string GetAccountName(this HttpSessionState state)
        {
            if (state != null && (state[ACCOUNTID] != null || state[ACCOUNTNAME] != null))
                return state[ACCOUNTNAME].ToString();
            return string.Empty;
        }

        public static Principal GetToken(this HttpSessionState state)
        {
            if (state != null && (state[ACCOUNTID] != null || state[ACCOUNTNAME] != null))
            {
                return new Principal(){
                                AccountId = Convert.ToInt64(state[ACCOUNTID]),
                                Username = state[ACCOUNTNAME].ToString(),
                                LastAction = Convert.ToInt64(state["&LastAction&"]),
                                Code = state[_CODE].ToString(),
                                AccessToken = state[_ACCESSSTOKEN].ToString(),
                                ExpriseTime = Convert.ToInt64(state[_EXPRISEDATE])
                            };
            }
            return null;
        }

        public static void SetPrincipal(this HttpSessionState state, Principal principal)
        {
            state[ACCOUNTID] = principal.AccountId;
            state[ACCOUNTNAME] = principal.Username;
            state["&LastAction&"] = principal.LastAction;
            state[_CODE] = principal.Code;
            state[_ACCESSSTOKEN] = principal.AccessToken;
            state[_EXPRISEDATE] = principal.ExpriseTime;
        }

        public static void RemovePricipal(this HttpSessionState state)
        {
            state.Clear();
            state.Abandon();
        }
                
        public static PortalUser GetUser(this HttpSessionState state)
        {
            if (Configurations.AUTHENTICATION_MODE)
            {
                if (HttpContext.Current.User != null)
                {
                    if (HttpContext.Current.User.Identity.IsAuthenticated)
                    {
                        if (HttpContext.Current.User.Identity is FormsIdentity)
                        {
                            FormsIdentity id = HttpContext.Current.User.Identity as FormsIdentity;
                            FormsAuthenticationTicket ticket = id.Ticket;
                            return JsonSerializer.DeserializeFromString<PortalUser>(ticket.UserData);
                        }
                    }
                }
            }
            else
            {
                if (state != null && state[ACCOUNTINFO] != null)
                    return (PortalUser)state[ACCOUNTINFO];
                else
                {
                    if (state[ACCOUNTNAME] != null)
                    {
                        string Username = state[ACCOUNTNAME].ToString();
                        if (!string.IsNullOrEmpty(Username))
                        {
                            PortalUser info = ManagerFactory.PortalUserManager.GetUser(Username);
                            if (info != null)
                            {                                
                                state[ACCOUNTINFO] = info;
                                return info;
                            }
                            else
                            {
                                int destuserId;
                                int.TryParse(state[ACCOUNTID].ToString(), out destuserId);
                                var userInfo = ManagerFactory.DAOEntity.Insert<PortalUser>(new PortalUser()
                                {
                                    NAME = Username,
                                    USERNAME = Username,
                                    JOINED = DateTime.Now,
                                    LASTVISIT = DateTime.Now,
                                    TIMEZONE = 0,
                                    ISAPPROVED = 1,
                                    IP = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].Trim(),
                                    SUSPENDED = DateTime.Now,
                                    PMNOTIFICATION = 1,
                                    LOSTPASSWORD = string.Empty,
                                    PASSWORD = string.Empty,
                                    DISPLAYNAME = Username,
                                    EMAIL = string.Empty,
                                    TEL = string.Empty,
                                    MOBILE = string.Empty,
                                    ADDRESS = string.Empty,
                                    ISSUPERADMIN = 0,
                                    AVATAR = AccountHelper.GetAvatarPath(Convert.ToInt64(destuserId), 50, 50),
                                    TYPE = (int)UserType.govn,
                                    DESTUSERID = destuserId,
                                });
                                if (userInfo != null)
                                {
                                    info = ManagerFactory.PortalUserManager.GetUser(Username);
                                    if (info != null)
                                    {
                                        state[ACCOUNTINFO] = info;
                                        return info;
                                    }
                                }
                            }
                        }
                    }
                }
            }             
            return null;
        }

        public static PortalPortal WorkingPortal(this HttpSessionState state)
        {
            if (state != null)
            {
                if (state[WORKING_PORTAL] != null)
                    return (PortalPortal)state[WORKING_PORTAL];
            }
            return null;
        }
        public static PortalPortal CurrentPortal(this HttpSessionState state, int portalId)
        {
            if (state != null)
            {
                if (state[string.Format(CURRENT_PORTAL, portalId)] != null)
                    return (PortalPortal)state[string.Format(CURRENT_PORTAL, portalId)];
            }
            return null;
        }
    }
}